package com.yzt.zhuju.webview;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.webkit.GeolocationPermissions;
import android.webkit.PermissionRequest;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

import androidx.core.content.ContextCompat;

import com.yzt.zhuju.R;
import com.yzt.zhuju.permission.PermissionsUtils;
import com.yzt.p_base.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * author : bob
 * date   : 2022/12/9
 * desc   :
 */
public class AppWebChromeClient extends WebChromeClient {

    public final static int FILE_CHOOSER_RESULT_CODE = 1;

    public final static int RECORD_VIDEO = 2;

    private final OnWebChromeListener mListener;

    private final Activity mContext;

    public AppWebChromeClient(Activity context, OnWebChromeListener listener) {
        mContext = context;
        mListener = listener;
    }

    @Override
    public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
        callback.invoke(origin, true, false);
        super.onGeolocationPermissionsShowPrompt(origin, callback);
    }

    @Override
    public void onPermissionRequest(PermissionRequest request) {
        String[] requestedResources = request.getResources();
        ArrayList<String> permissions = new ArrayList<>();
        ArrayList<String> grantedPermissions = new ArrayList<>();
        for (String requestedResource : requestedResources) {
            switch (requestedResource) {
                case PermissionRequest.RESOURCE_AUDIO_CAPTURE:
                    permissions.add(Manifest.permission.RECORD_AUDIO);
                    break;
                case PermissionRequest.RESOURCE_VIDEO_CAPTURE:
                    permissions.add(Manifest.permission.CAMERA);
                    break;
                case PermissionRequest.RESOURCE_PROTECTED_MEDIA_ID:
                    permissions.add(PermissionRequest.RESOURCE_PROTECTED_MEDIA_ID);
                    break;
                default:
                    break;
            }
        }

        for (int i = 0; i < permissions.size(); i++) {
            if (!permissions.get(i).equals(PermissionRequest.RESOURCE_PROTECTED_MEDIA_ID)) {
                if (ContextCompat.checkSelfPermission(mContext, permissions.get(i)) != PackageManager.PERMISSION_GRANTED) {
                    continue;
                }
            }
            switch (permissions.get(i)) {
                case Manifest.permission.RECORD_AUDIO:
                    grantedPermissions.add(PermissionRequest.RESOURCE_AUDIO_CAPTURE);
                    break;
                case Manifest.permission.CAMERA:
                    grantedPermissions.add(PermissionRequest.RESOURCE_VIDEO_CAPTURE);
                    break;
                case PermissionRequest.RESOURCE_PROTECTED_MEDIA_ID:
                    grantedPermissions.add(PermissionRequest.RESOURCE_PROTECTED_MEDIA_ID);
                    break;
                default:
                    break;
            }
        }

        if (grantedPermissions.isEmpty()) {
            request.deny();
        } else {
            String[] grantedPermissionsArray = new String[grantedPermissions.size()];
            grantedPermissionsArray = grantedPermissions.toArray(grantedPermissionsArray);
            request.grant(grantedPermissionsArray);
        }
    }

    @Override
    public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {

        String[] permissions;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
            permissions = new String[]{
                    Manifest.permission.CAMERA,
                    Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.READ_MEDIA_AUDIO,
                    Manifest.permission.READ_MEDIA_IMAGES,
                    Manifest.permission.READ_MEDIA_VIDEO};
        } else {
            permissions = new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE};
        }

        PermissionsUtils.getInstance().checkPermission(mContext, permissions, "图片、语音、视频文件选择上传", new PermissionsUtils.OnCallBackListener() {
            @Override
            public void open(List<String> list) {
                if (mListener != null) {
                    mListener.onShowFileChooser(filePathCallback);
                }
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");

                String type = fileChooserParams.getAcceptTypes()[0];

                if (!TextUtils.isEmpty(type)) {
                    i.setType(type);
                    //如果是打开图片
                    if ("image/*".equals(type)) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                            i.addCategory(Intent.CATEGORY_OPENABLE);
                        }
                    } else if ("video/*".equals(type)) {
                        if (fileChooserParams.isCaptureEnabled()) {
                            // 走相机
                            startCameraIntent(RECORD_VIDEO);
                        } else {
                            // 走相册，遍历出视频
                            selectVideoIntent(RECORD_VIDEO);
//                            i.setType("video/*");
                        }
                        return;
                    }
                } else {
                    //如果是打开所有文件
                    i.setType("*/*");
                }
                mContext.startActivityForResult(Intent.createChooser(i, mContext.getString(R.string.choose_file)), FILE_CHOOSER_RESULT_CODE);
            }

            @Override
            public void notOpen(List<String> list, String label) {
                ToastUtil.showMessage(mContext.getString(R.string.go_set_open_permission));
                if (filePathCallback != null) {
                    filePathCallback.onReceiveValue(null);
                }
            }
        });
        return true;
    }

    /**
     * 调起相机
     */
    private void startCameraIntent(int requestCode) {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 60);
        //开启摄像机
        mContext.startActivityForResult(intent, requestCode);
    }

    private void selectVideoIntent(int requestCode) {
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
        mContext.startActivityForResult(intent, requestCode);
    }

    public interface OnWebChromeListener {

        void onOpenFileChooser(ValueCallback<Uri> uploadMsg);

        void onShowFileChooser(ValueCallback<Uri[]> filePathCallback);
    }
}

